package com.moore.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import static com.moore.utils.Logger.toLog;

@Controller
@RequestMapping("/upload")
public class FileUploadController {

    @PostMapping
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        toLog("正在上传文件");
        if (file.isEmpty()) {
            toLog("文件为空");
            return "上传失败，请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String suffixName = null;
        if (fileName != null) {
            suffixName = fileName.substring(fileName.lastIndexOf("."));
        }
        String uploadDir = request.getServletContext().getRealPath("/WEB-INF/views/resources/uploads/");
        File uploadDirFile = new File(uploadDir);
        if (!uploadDirFile.exists()) {
            toLog("文件夹不存在，创建目录");
            uploadDirFile.mkdirs();
        }
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(uploadDir + fileName);
        try {
            file.transferTo(dest);
            // 返回相对路径
            String relativePath = "/resources/uploads/" + fileName;
            toLog("文件上传完成，路径为" + relativePath);
            return relativePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        toLog("文件上传失败");
        return "上传失败！";
    }

}
